package com.jvm;

/**
 * 双线程打印奇偶数
 */
public class CrossNum {
    public  volatile int num = 1;
    public  volatile boolean flag = false;

    public static void main(String[] args) {
        CrossNum cNum = new CrossNum();
        Thread thread01 = new Thread(new Print2nAnd1(cNum));
        Thread thread02 = new Thread(new Print2n(cNum));
        thread01.start();
        thread02.start();
    }
}

class Print2nAnd1 implements Runnable{
    private CrossNum cNum;
    public Print2nAnd1(CrossNum cNum) {
        // TODO Auto-generated constructor stub
        this.cNum = cNum;
    }

    @Override
    public void run() {
        while(cNum.num<101) {
            if(!cNum.flag) {
                System.out.println("奇数线程"+Thread.currentThread()+cNum.num);
                cNum.num++;
                cNum.flag = true;
                // notifyAll();
            }
        }

    }
}

class Print2n implements Runnable{
    private CrossNum cNum;
    public Print2n(CrossNum cNum) {
        // TODO Auto-generated constructor stub
        this.cNum = cNum;
    }

    @Override
    public void run() {
        while(cNum.num<101) {
            if(cNum.flag) {
                System.out.println("偶数线程"+Thread.currentThread()+cNum.num);
                cNum.num++;
                cNum.flag = false;
            }
        }

    }
}
